package com.orhon.smartcampus.modules.user.dao;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.modules.user.entity.Token;
import com.orhon.smartcampus.utils.R;

@Service
public class TokenService {

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Autowired
    private TokenDao tokenDao;
    
    @Autowired
    private HttpServletRequest request;

    public String getSystemToken(){
    	
    	String token = request.getHeader("token");
    	
       // String token = (String) SecurityUtils.getSubject().getPrincipal();
        return token;
    }


    public R createJwtToken(String userName , Long userId,  Long schoolId,String userType) throws Exception {

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);


        String token_str = JwtUtils.sign(userName , userId , schoolId , "OrhonSmartCampusToken7893" , expireTime, userType);

        Token token = tokenDao.queryByUserId(userId);

        if (token == null){
            Token t = new Token();
            t.setUserid(userId);
            t.setToken(token_str);
            t.setExpire_time(expireTime);
            t.setUsername(userName);
            t.setUpdate_time(now);
            tokenDao.save(t);
        }
        else{
            //token = tokenDao.get(Token.class , userId);
            token.setUserid(userId);
            token.setUpdate_time(now);
            token.setExpire_time(expireTime);
            token.setUsername(userName);
            token.setToken(token_str);
            tokenDao.saveOrUpdate(token);
        }


        return R.ok().put("token" , token_str).put("expire" , expireTime);
    }


}
